package com.gliese.renren.util;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Properties;

import com.gliese.util.file.FileReaderHelper;
import com.gliese.util.file.FileWriterHelper;

public class RenrenPropertiesUtil {
	private  static HashSet<String> toViewIds;
	private static HashSet<String> hasViewIds;
	static {
		toViewIds = prepareToViewProfileIds();
		hasViewIds= prepareHasViewProfileIds();
	}
	
	private static HashSet<String> prepareProfileIds(String classPath, String keyStr) {
		HashSet<String> hsIds = new HashSet<String>();
		Properties proFriends = new Properties();
		try {
			proFriends.load(FileReaderHelper.readFromClassPath(classPath));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		String[] keys = proFriends.get(keyStr).toString().split(", ");
		for (String key : keys) {
			hsIds.add(key);
		}
		return hsIds;
	}

	public synchronized static HashSet<String> getToViewIds() {
		return toViewIds;
	}

	public synchronized static HashSet<String> getHasViewIds() {
		return hasViewIds;
	}

	public static HashSet<String> prepareToViewProfileIds() {
		return prepareProfileIds("toViewFriends.properties", "toViewIds");
	}

	public static HashSet<String> prepareHasViewProfileIds() {
		return prepareProfileIds("hasViewedFriends.properties", "hasViewIds");
	}

	private  static void storeProfileIds(HashSet<String> hs,String key,String classPath) throws IOException {
		Properties proFirendIds =  new Properties();
		String preStr = hs.toString();
		int length = preStr.length();
		if(length==0 ) return ;
		String value = preStr.substring(1,length-1 );
		proFirendIds.put(key, value);
		Writer writer = FileWriterHelper.wirteToClassPath(classPath);
		if(writer!=null)
		proFirendIds.store(writer, key);
	}
	public static void storeToViewProfileIds() throws IOException{
		storeProfileIds(getToViewIds(), "toViewIds", "/toViewFriends.properties");
		
	}
	public static void storeHasViewProfileIds() throws IOException{
		storeProfileIds(getHasViewIds(), "hasViewIds", "/hasViewedFriends.properties");
		
	}
}
